<template>
  <div>
     <Row :gutter="16" type="flex" class="ivu-mb-16">
          <Col span="1" class="label">
            <span>时间: </span>
          </Col>
          <Col>
            <div class="time">
                <Button @click="timeButtons(0)" :type="timeButton==0?'primary':'default'" :ghost="timeButton==0" class="ivu-mr-8">今日</Button>
                <Button @click="timeButtons(1)" :type="timeButton==1?'primary':'default'" :ghost="timeButton==1" :disabled="this.$Date().date()<=1" class="ivu-mr-8">昨日</Button>
                <Button @click="timeButtons(2)" :type="timeButton==2?'primary':'default'" :ghost="timeButton==2" :disabled="this.$Date().date()<=2" class="ivu-mr-8">前日</Button>
                <!-- <Button>今日</Button>
                <Button>昨日</Button>
                <Button>近7日</Button> -->
                <DatePicker transfer :options="options" v-model="serchForm.date" format="yyyy/MM/dd" type="date" placement="bottom-end" placeholder="自定义时间" style="width: 200px" @on-change="changeDate"></DatePicker>
            </div>
          </Col>
          <Col class="label">
            <span>请求类型: </span>
             <Select v-model="serchForm.request" style="width:120px" placeholder="请选择类型" @on-change="changeselect" clearable>
              <Option v-for="item in serverList" :value="item.value" :key="item.value">{{ item.label }}</Option>
            </Select>
          </Col>
          <Col class="label">
            <span>状态码：</span>
              <Select v-model="serchForm.status_code" style="width:120px" placeholder="请选择类型" @on-change="changestatus" clearable>
                <Option v-for="it in statusList" :value="it.value" :key="it.value">{{ it.label }}</Option>
              </Select>
          </Col>
          <Col >
            <Input v-model="serchForm.keyword" placeholder="请输入URL地址，如/filepath" @on-change="changeDomian" clearable></Input>
          </Col>
          <Col  class="mdicon">
            <Icon type="md-refresh"  @click="changeRefresh" />
          </Col>
          <Col>
             <Button type="primary"  @click="changeModal">下载日志</Button>
          </Col>
      </Row>

    <Table :columns="columns" :data="tableData" :loading="tableLoading" style="margin-top:10px" @on-sort-change="sortchange" max-height="600"></Table>
    <div style="text-align: center;margin-top: 10px;">
       <Page transfer :current.sync="currentPage" :total="total" :page-size="pageSize" :page-size-opts="pageSizeArray" show-sizer show-total show-elevator @on-change="changePage" @on-page-size-change="changePageSize"/>
    </div>
    <Modal :width="600" v-model='modalStatus' title='下载' transfer :mask-closable='false' @on-cancel='canceledit()' footer-hide>
        <span>时间：</span>
        <Button @click="changetimeButtons(0)" :type="changetimeButton==0?'primary':'default'" :ghost="changetimeButton==0"  class="ivu-mr-8">按月</Button>
        <Button @click="changetimeButtons(1)" :type="changetimeButton==1?'primary':'default'" :ghost="changetimeButton==1" class="ivu-mr-8">按日期</Button>
        <DatePicker v-model="serchForm.timedate" format="yyyy/MM/dd"  :options="optionsdaterange" type="daterange" placement="bottom-end" placeholder="自定义时间" style="width: 240px"  v-if="changetimeButton==1"></DatePicker>
        <DatePicker v-model="serchForm.month_time" format="yyyy/MM" :options="optionsmonth" type="month" placement="bottom-end" placeholder="自定义时间" style="width: 240px" v-if="changetimeButton==0"></DatePicker>
        <div class="ivu-mt-16" style="text-align: center;">
             <Button type="primary"  @click="clickupload">下载日志</Button>
        </div>

    </Modal>
  </div>
</template>
<script>

    import{getlogList} from '@api/httpsetting'

    export default {
        data () {
            return {
                timeout:null,
                changetimeButton: 1,
                modalStatus: false,
                serchForm: {
                    keyword:'',
                    date:new Date(),
                    log_type:2,
                    status_code:'',
                    request:'',
                    keyword:'',
                    timedate:[new Date(),new Date()],
                    month_time:'',
                },
                timeButton: 0,
                serverList: [

                    {
                        value: '',
                        label: '所有'
                    },
                    {
                        value: 'GET',
                        label: 'GET'
                    },
                    {
                        value: 'POST',
                        label: 'POST'
                    },
                    {
                        value: 'HEAD',
                        label: 'HEAD'
                    },
                    {
                        value: 'PUT',
                        label: 'PUT'
                    },
                    {
                        value: 'DELETE',
                        label: 'DELETE'
                    }
                ],
                statusList:[
                    {
                        value: '',
                        label: '所有'
                    },
                    {
                        value: '200',
                        label: '200'
                    },
                     {
                        value: '301',
                        label: '301'
                    },
                     {
                        value: '404',
                        label: '404'
                    },
                     {
                        value: '500',
                        label: '500'
                    },
                     {
                        value: '502',
                        label: '502'
                    },
                     {
                        value: '503',
                        label: '503'
                    },
                     {
                        value: '504',
                        label: '504'
                    },
                ],
                tableData: [],
                tableLoading: false,
                columns: [
                    {
                        title: '序号',
                        minWidth: 70,
                        align: 'center',
                        render: (h, params) => h('span', params.index + 1)

                    },
                    {
                        title: '时间',
                        minWidth: 200,
                        align: 'center',
                        key: 'date_time',

                    },
                    {
                        title: 'IP',
                        minWidth: 160,
                        align: 'center',
                        key: 'ip',

                    },
                    {
                        title: '操作系统',
                        minWidth: 120,
                        key: 'system',
                        align: 'center',

                    },
                    {
                        title: '类型',
                        minWidth: 100,
                        key: 'request',
                        align: 'center',

                    },
                    {
                        title: '状态',
                        minWidth: 100,
                        align: 'center',
                        key: 'status_code',

                    },
                    {
                        title: '协议',
                        minWidth: 100,
                        align: 'center',
                        key: 'agreement',

                    },
                    {
                        title: 'URL',
                        minWidth: 280,
                        key: 'url',
                        align: 'center',
                        tooltip:true
                        // key: 'platform'

                    },
                    {
                        title: '响应大小',
                        minWidth: 120,
                        align: 'center',
                        key: 'response_size',
                        tooltip: true

                    },

                ],
                currentPage: 1,
                total: 0,
                pageSize: 100,
                pageSizeArray: [10, 20, 50, 100, 200, 300],
                modalForm: {
                    remark: ''
                },
                rules: {
                    remark: [{ required: true, message: '请输入备注', trigger: 'blur' }]
                },
                subloading: false,
                options:{
                     disabledDate (date) {
                        let dateTime = new Date();
                        let currentYear = dateTime.getFullYear();
                        let currentMonth = dateTime.getMonth();
                        let monthFirstDay = new Date(currentYear, currentMonth, 1);

                        let newMonth = ++currentMonth;
                        let newYear = currentYear;
                        if (newMonth >= 12) {
                            newMonth -= 12;
                            newYear++;
                        }
                        let nextMonthFirst = new Date(newYear, newMonth, 1);
                        let nonthLastDay = new Date(
                            nextMonthFirst.getTime() - 24 * 60 * 60 * 1000
                        );
                        return (
                            date.valueOf() < new Date(monthFirstDay).getTime() ||
                            date.valueOf() >new Date().getTime()
                        );
                            
                        //   return date && date.valueOf() > Date.now();
                        // var dateNow = new Date();
                        // return date && date.valueOf() > dateNow.setMonth(dateNow.getMonth() - 1);
                        //   return date && ((date.getTime() + 24 * 60 * 60 * 1000 < new Date().getTime()) || date.getTime() > (new Date().getTime() + 31 * 24 * 60 * 60 * 1000));
                        //   return date && ((date.getTime() + 24 * 60 * 60 * 1000*30 < new Date().getTime()) || date.getTime() > (new Date().getTime() ));
                        // return (date.getTime() < (new Date().getTime() - 4 * 24 * 60 * 60 * 1000)) || date.getMonth() < new Date().getMonth() || date.getTime() > new Date().getTime();
                    }
                },
                optionsmonth:{
                     disabledDate (date) {
                        //  let nextMonthFirst = new Date(newYear, newMonth, 1);
                        // let nonthLastDay = new Date(
                        //     nextMonthFirst.getTime() - 24 * 60 * 60 * 1000
                        // );
                        return ( this.$Date(date.valueOf()).year()< this.$Date().year()-1)||(this.$Date().year()< this.$Date(date.valueOf()).year())||( this.$Date(date.valueOf()).month()>new Date().getMonth()-1)
                        //  return  date.valueOf()<new Date(newYear, newMonth, 1)|| date.valueOf()  > Date.now();
                     }
                },
                optionsdaterange:{
                     disabledDate (date) {
                          let dateTime = new Date();
                        let currentYear = dateTime.getFullYear();
                        let currentMonth = dateTime.getMonth();
                        let monthFirstDay = new Date(currentYear, currentMonth, 1);

                        let newMonth = ++currentMonth;
                        let newYear = currentYear;
                        if (newMonth >= 12) {
                            newMonth -= 12;
                            newYear++;
                        }
                        let nextMonthFirst = new Date(newYear, newMonth, 1);
                        let nonthLastDay = new Date(
                            nextMonthFirst.getTime() - 24 * 60 * 60 * 1000
                        );
                        return (
                            date.valueOf() < new Date(monthFirstDay).getTime() ||
                            date.valueOf() > new Date().getTime()
                        );
                        //   return date && ((date.getTime() + 24 * 60 * 60 * 1000*30 < new Date().getTime()) || date.getTime() > (new Date().getTime() ));
                     }
                }
            }
        },
        methods: {
            initial(row){
                console.log(this.$Date().date())
                this.$set(this.serchForm,'site_id',row.id)
                this._demianList()
                this.serchForm.month_time=this.$Date().subtract(1,'month').format('YYYY-MM')
            },
            timeButtons (num) {
                // console.log(this.$Date().subtract(num, 'day'),'day')
                if(num==0){
                    this.serchForm.date=this.$Date(new Date()).format('YYYY-MM-DD')
                }else if(num==1){
                    let date = new Date()
                    date.setTime(date.getTime() - 3600 * 1000 * 24)
                    this.serchForm.date = this.$Date(date).format('YYYY-MM-DD')
                }else{
                    let date = new Date()
                    date.setTime(date.getTime() - 3600 * 1000 * 24*2)
                    this.serchForm.date = this.$Date(date).format('YYYY-MM-DD')
                }
                this.timeButton = num
                this._demianList()
            },
            changeDate(val){
                this.serchForm.date= val?this.$Date(val).format('YYYY-MM-DD'):''
                this.timeButton=null
                // console.log(this.$Date(val).format('YYYY-MM-DD'),'val')
                this._demianList()

            },
            changePage (index) {
                this.currentPage = index;
                this._demianList()
            },
            changePageSize (val) {
                this.pageSize = val;
                this._demianList()
            },
            changeDomian () {
                this._demianList()
            },
            changeselect () {
                this._demianList()
            },
            changestatus(){
                this._demianList()
            },
            // 排序
            sortchange (e) {
            },
            // 获取列表数据
            _demianList () {
                let params = {
                    site_id:this.serchForm.site_id,
                    log_type:2,
                    keyword:this.serchForm.keyword,
                    date:this.serchForm.date?this.$Date(this.serchForm.date).format('YYYY-MM-DD'):'',
                    status_code:this.serchForm.status_code,
                    request:this.serchForm.request,
                    keyword:this.serchForm.keyword,
                    page: this.currentPage,
                    pageSize: this.pageSize
                }
                this.tableLoading = true
                getlogList(params).then(res => {
                    this.tableData = res.list;
                    this.total = res.total;
                    this.tableLoading = false;
                }).catch(() => {
                    this.tableLoading = false
                })
                this.currentPage = 1;
            },
            changeModal () {
                this.modalStatus = true
            },
            canceledit () {
                this.modalStatus = false
                this.serchForm.timedate=[new Date(),new Date()],
                this.serchForm.month_time=this.$Date().subtract(1,'month').format('YYYY-MM'),
                this.changetimeButton=1
            },
            // 间隔刷新10s
            changeRefresh () {
                this.throttle(this._demianList);
            },
         
            throttle(func, wait = 10000, immediate = false) {
                if (this.timeout !== null) clearTimeout(this.timeout);
                    // 立即执行，此类情况一般用不到
                    if (immediate) {
                        var callNow = !this.timeout;
                        this.timeout = setTimeout(function() {
                            this.timeout = null;
                        }, wait);
                        if (callNow) typeof func === 'function' && func();
                    } else {
                         this.tableLoading = true
                        // 设置定时器，当最后一次操作后，timeout不会再被清除，所以在延时wait毫秒后执行func回调方法
                        this.timeout = setTimeout(function() {
                            typeof func === 'function' && func();
                             this.tableLoading = false
                        }, wait);
                    }
            },
            changetimeButtons (num) {
                this.changetimeButton = num
            },
            clickupload () {
                let url = `${process.env.VUE_APP_API}/v1/site/index/download-access-log?`
                let urls = `id=${this.serchForm.site_id}&type=${this.changetimeButton===0 ? 'month' : 'day'}&month_time=${this.serchForm.month_time ? this.$Date(this.serchForm.month_time).format('YYYY-MM') : ''}&start_time=${this.serchForm.timedate[0] ? this.$Date(this.serchForm.timedate[0]).format('YYYY-MM-DD'): ''}&end_time=${this.serchForm.timedate[1] ? this.$Date(this.serchForm.timedate[1]).format('YYYY-MM-DD') : ''}`
                // console.log(`${url}${urls}`)
                window.open(`${url}${urls}`)
            }

        }
    }
</script>
<style scoped>
.label{
    line-height: 30px;
    text-align: center;
    margin-bottom: 5px;
}
.mdicon{
    text-align: center;
    font-size: 28px;
    line-height: 30px;
    cursor: pointer;
}
.time{
    display: flex;
}
</style>
